interface PrioritizedTask {
  task: () => any;
  priority: number;
}

/**
 * 表示在空闲时间执行任务的任务队列。
 */
class IdleTaskQueue {
  private tasks: PrioritizedTask[];
  private isRunning: boolean;

  constructor() {
    this.tasks = [];
    this.isRunning = false;
  }

  public addTask(task: () => any, priority: number = 0): void {
    this.tasks.push({ task, priority });
    this.sortTasks();
    this.run();
  }

  private sortTasks(): void {
    this.tasks.sort((a, b) => a.priority - b.priority);
  }

  private run(): void {
    if (this.isRunning || this.tasks.length === 0)
      return;

    this.isRunning = true;
    this.scheduleNext();
  }

  private scheduleNext(): void {
    requestIdleCallback(async (deadline: IdleDeadline) => {
      if (deadline.timeRemaining() > 0 && this.tasks.length > 0) {
        const { task } = this.tasks.shift()!;
        try {
          await task();
        }
        catch (error) {
          console.error('Task execution failed:', error);
        }
        this.scheduleNext();
      }
      else {
        this.isRunning = false;
        if (this.tasks.length > 0) {
          this.run();
        }
      }
    }, { timeout: 1000 });
  }
}
export const idleTaskQueue = new IdleTaskQueue();
